package name.cyrax.red.jpv.impl.funcs.contexts;

import java.util.List;

import name.cyrax.red.jpv.api.adapters.CalculationContext;
import name.cyrax.red.jpv.api.adapters.PrepareAdapter;
import name.cyrax.red.jpv.api.funcs.InvocationContext;

public final class PreparingInvocationContext implements InvocationContext
{
	private final InvocationContext parentContext;
	private final PrepareAdapter[] prepareables;

	private PreparingInvocationContext(InvocationContext parentContext, PrepareAdapter[] prepareables) {
		this.parentContext = parentContext;
		this.prepareables = prepareables;			
	}
	
	public static InvocationContext newInstance(InvocationContext parentContext, List<PrepareAdapter> prepareables) {
		if (prepareables == null || prepareables.isEmpty())
			return parentContext;
		return new PreparingInvocationContext(parentContext, prepareables.toArray(new PrepareAdapter[prepareables.size()]));
	}
	
	public static InvocationContext newInstance(InvocationContext parentContext, PrepareAdapter[] prepareables) {
		if (prepareables == null || prepareables.length <= 0)
			return parentContext;
		return new PreparingInvocationContext(parentContext, prepareables);
	}
	
	@Override public CalculationContext getCalculationContext()
	{
		return parentContext.getCalculationContext();
	}

	@Override public void beginCalc()
	{
		parentContext.beginCalc();
		CalculationContext c = getCalculationContext();
		for (PrepareAdapter a: prepareables)
			a.beginCalc(c);
	}

	@Override public void endCalc()
	{
		parentContext.endCalc();
		CalculationContext c = getCalculationContext();
		for (PrepareAdapter a: prepareables)
			a.beginCalc(c);
	}
}
